package com.yecheng.yeaiagent.advisor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.ai.chat.model.MessageAggregator;
import reactor.core.publisher.Flux;

@Slf4j
public class MyLoggerAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

    private AdvisedRequest before(AdvisedRequest request){
        log.info("AI Request:{}",request.userText());
        return request;
    }

    private void after(AdvisedResponse response){
        log.info("AI Response:{}",response.response().getResult().getOutput().getText());
    }

    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        AdvisedRequest request = this.before(advisedRequest);
        AdvisedResponse response = chain.nextAroundCall(request);
        this.after(response);
        return response;
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        AdvisedRequest request = this.before(advisedRequest);
        Flux<AdvisedResponse> responseFlux = chain.nextAroundStream(request);
        return (new MessageAggregator()).aggregateAdvisedResponse(responseFlux,this::after);
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
